<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\common\model\oms;

use app\common\model\jooj_member\ViewMemberIndex;
use app\common\model\jooj_member\MemberIndex;
use app\common\arvato\CommonPush;

/**
 * Description of MemberSign
 *
 * @author Expect
 */
class MemberSign extends Base {

    protected $base_table = 'member_sign';
    protected $table = 'member_sign';
    protected $connection = ['database' => 'oms'];
    private $companyId;

    public function __construct($data = []) {
        $this->companyId = $data;
        if (!is_array($data)) {
            $this->table = $this->base_table . '_' . $data;
        }
        $data = is_array($data) ? $data : [];
        parent::__construct($data);
    }

    /**
     * 获取当天签到列表
     * @param type $serviceStore
     */
    public function getMemberSignList($serviceStore, $params) {
        if (empty($serviceStore)) {
            return false;
        }
        $page = $params['page'] ? $params['page'] : 1;
        $pageSize = $params['size'] ? $params['size'] : 1;
        $where = [
            'service_store' => $serviceStore, //服务门店
            'start_time'    => [['>', strtotime(date('Y-m-d 00:00:00'))], ['<', strtotime(date('Y-m-d 23:59:59'))], 'and']//当天时间
        ];
        $count = $this->getPageCount($where);
        $pageList = $this->getPageCount($where, 0, $page, $pageSize, 'ms_id as queue_id, member_code,vip_id,y_id,status,start_time,ms_id,service_p,come_from', $order = 'ms_id desc');
        $memberData = $this->getMemberService($pageList);
        $data = [
            'totalCount' => (string) $count,
            'totalPage'  => (string) ceil($count / $pageSize),
            'page'       => (string) $page,
            'pageSize'   => (string) $pageSize,
            'list'       => $memberData,
        ];
        return $data;
    }

    /**
     * 获取分页数据和count
     * @param type $where
     * @param type $is_count
     * @param type $page
     * @param type $pageSize
     * @param type $field
     * @return type
     */
    private function getPageCount($where, $is_count = 1, $page = 1, $pageSize = 2, $field = "*", $order = '') {
        if ($is_count) {
            return $this->where($where)->count();
        }
        $ret = $this->where($where)->page($page, $pageSize)->order($order)->column($field);
        return $ret;
    }

    private function getMemberService($data) {
        $viewMemberModel = new ViewMemberIndex($this->companyId);
        if (false === empty($data)) {
            foreach ($data as $k => $v) {
                //获得信息
                $userinfos = $viewMemberModel->getIndexAndvipData(['member_code' => $v['member_code']]);
                if ($userinfos) {
                    $userinfos = $this->dataInit($userinfos, true);
                    $userinfos['memberCode'] = $v['member_code'];
                    $returnInfo = $this->checkDataIntegrity($userinfos);
                } else {
                    $returnInfo = (object) [];
                }
                $data[$k]['userinfos'] = $returnInfo;
            }
            foreach ($data as $key => $value) {
                $data[$key] = $this->convertUnderline($value);
            }
            return array_values($data);
        }
        return [];
    }

    /**
     * 会员签到
     * @param type $params
     */
    public function memberCheckin($params,$CompanyCode) {
        
        $this->closeOtherService($params['member_code']);
        //开始今天的服务
        //检查这个会员，在此门店今天内是否已经在服务
        $where = array(
            'member_code'   => $params['member_code'],
            'type'          => 1,
            'service_store' => $params['service_store'],
            'status'        => ['IN', '1,2'],
            'start_time'    => [['EGT', strtotime(date('Y-m-d 00:00:00'))], ['ELT', strtotime(date('Y-m-d 23:59:59'))], 'and'], //大于今天凌晨00:00:00的
        );
        $result = $this->where($where)->column('ms_id,add_ts');
        //此门店，今天内已有未结束的服务
        if ($result) {
            return false;
        }
        //先结束此会员在其他门店未完成的服务
        unset($where['service_store']);
        $this->where($where)->data(['status' => 3, 'end_time' => time()])->update();

        $value = [
            'member_code'   => $params['member_code'],
            'type'          => 1,
            'status'        => 2,
            'come_from'     => $params['come_from'],
            'service_store' => $params['service_store'],
            'service_p'     => $params['service_p'],
            'start_time'    => time(),
            'add_ts'        => time(),
        ];
        if (!empty($params['vip_id'])) {
            $value['vip_id'] = $params['vip_id'];
        }
        //如果来源有空，就根据数据自己添加
        if (empty($value['come_from'])) {
            if (!empty($value['service_store']) || !empty($value['service_p'])) {
                $value['come_from'] = 2; //都来源扫一扫
            }
        }

        $value = array_diff($value, ['', false]); //去掉空值    
        $serviceId = $this->insertGetId($value);
        if (!$serviceId) {
            return false;
        }
        //仅宝岛的才会推送
        if ($CompanyCode == 'baodao') {
            $memberModel = new ViewMemberIndex($this->companyId);
            $memberInfo = current($memberModel->getViewInfoByCondition(['member_code' => $params['member_code']]));
            $commonPush = new CommonPush();
			$storeModel = new Store();
            $shopCode = $storeModel->where(['store_id' => $params['service_store']])->value('trusteeship_id');
            $cardno = !empty($params['cardno']) ? $params['cardno'] : $memberInfo['cardno'];
            $mobile = !empty($params['mobile']) ? $params['mobile'] : $memberInfo['mobile'];
            $data = ['mobile' => $mobile, 'queue_id' => $serviceId, 'openid' => $memberInfo['account_code'], 'card_no' => $cardno, 'shop_code' => $shopCode, 'sign_time' => date('Y/m/d H:i:s'), 'sign_type' => '1', 'res_id' => ''];
            if ($params['yId']) {//如果是预约
                $data['ms_id'] = $params['yId'];
                $data['sign_type'] = '2';
            }
            $commonPush->pushToRedis($data, 'memberSignIn');
        }

        return ['msId' => $serviceId, 'status' => $value['status']];
    }

    /**
     * 关闭所有非今天未完成的服务(不管哪个门店，不管是普通还是预约服务)
     * 
     * @param   string      $companyCode        集团编码
     * @param   string      $vipId              针对某个集团会员
     * 
     */
    function closeOtherService($memberCode) {
        $where = [
            'status'     => ['IN', '1,2'],
            'start_time' => ['<=', strtotime(date('Y-m-d 00:00:00'))], //小于今天凌晨00:00:00的
        ];
        if (!empty($memberCode)) {
            $where['member_code'] = $memberCode;
        }
        $count = $this->getPageCount($where);
        if ($count < 1) {
            return false;
        }
        $res = $this->where($where)->update(['status' => 3, 'end_time' => time()]);
        if (!$res) {
            return false;
        }
        return $count;
    }

    /**
     * 获取最后一条记录
     * @param type $condition
     * @param type $field
     * @param type $status
     * @return type
     */
    public function findOneServiceDataDesc($condition, $field = '*', $status = true) {
        if ($status) {
            $serverWhere['add_ts'] = [['ELT', strtotime(date('Y-m-d 23:59:59'))], ['EGT', strtotime(date('Y-m-d 00:00:00'))]];
            $condition = array_merge($serverWhere, $condition);
        }
        return current($this->where($condition)->order('ms_id desc')->column($field));
    }

    /**
     * 获取签到信息
     * @param type $condition
     * @param type $field
     * @return type
     */
    public function getMemberSignListByCodition($condition, $field = '*') {
        return $this->where($condition)->order('ms_id desc')->column($field);
    }

    /**
     * 通过条件获取会员的签到信息
     * @param type $condition
     */
    public function getMemberSignByCondition($condition, $field = '*') {
        return $this->where($condition)->field($field)->find();
    }

    /**
     * 添加签到
     * @param type $data
     * @return type
     */
    public function addMemberSign($data) {
        return $this->insertGetId($data);
    }

    public function getMemberSignByYidOrMsId($where, $whereOr, $field = '*') {
        return $this->field($field)->where($where)->whereOr($whereOr)->find();
    }

    /**
     * 保存或者新增
     * @param type $data
     * @param type $where
     * @return type
     */
    public function saveMemberSign($data, $where) {
        $save = $this->save($data, $where);
        return $save;
    }

}
